<template>
  <main>
    <div class="dialogTitle" title="购物车订单" width="627px">
      <el-table :data="shopCart" :show-header="false">
        <el-table-column width="120" align="center">
          <template slot-scope="{ row }">
            <el-image style="width: 98px; height: 60px" :src="baseurl + '/' + row.img"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="title" width="200" align="left"></el-table-column>
        <el-table-column width="150" align="center" show-header="false">
          <template slot-scope="{ row }">
            <el-input-number :min="1" size="mini" v-model="row.num" @change="handleNum(row.id, row.num)"></el-input-number>
          </template>
        </el-table-column>

        <el-table-column width="150" align="center">
          <template slot-scope="{ row }">
            <el-input
              placeholder="请输入颜色"
              v-model="row.color"
              clearable
            >
            </el-input>
          </template>
        </el-table-column>

        <el-table-column align="center" show-header="false">
          <template slot-scope="{row}">

              <el-popconfirm confirm-button-text="确认" cancel-button-text="取消" title="确认删除当前花型？" @confirm="Orderblockdelete(row.id, row.uuid)">
                <el-button type="danger" slot="reference">删除</el-button>
              </el-popconfirm>

          </template>
        </el-table-column>
      </el-table>
      <div>
        <el-form ref="order" :inline="true" :model="order">
          <div class="dialogflex">
            <el-form-item style="margin-left: 20px;" label="要求交期" prop="delivery_date" :rules="[{ required: true, message: '要求交期不能为空' }]">
              <el-date-picker v-model="order.delivery_date" type="date" placeholder="选择日期"></el-date-picker>
            </el-form-item>
          </div>
          <div class="OrderSelectionCustomer dialogflex" v-if="session.role_id == 1 || session.role_id == 3 || session.role_id == 4 || session.role_id ==5 || session.role_id ==6">
            <el-form-item style="margin-left: 20px;" label="选择客户" prop="cstmr_name" :rules="[{ required: true, message: '客户不能为空' }]">
              <el-select v-model="order.cstmr_name" filterable placeholder="请选择" @change="changeCustomer">
                <el-option v-for="item in customers" :key="item.id" :label="item.username" :value="item"></el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button style="margin-left: 20px;" type="primary" @click="OrderIsBuy">确认下单</el-button>
      </span>
    </div>
  </main>
</template>


<script>
import { Message } from "element-ui";
import { cartList, cartDelete, cartNum, cartAdd } from "@/app/api/shopcat";
import { patternSearch, imageSearch } from "@/app/api/pattern";
import { searchCustomer } from "@/app/api/system";
import { orderAdd,OrderIsBuy } from "@/app/api/order";
import { mapState } from "vuex";
import { getProperty } from "@/app/api/property";
import { getConfigJSON } from "@/app/api/config";

export default {
  data() {
    return {
      customers: [],
      loading1: false,
      order: {
        delivery_date: "",
        cstmr_name: "",
      },
      getListData: {
        pageNo: 1,
        pageSize: 20,
        useradio: "",
        ClothingStyleradio: "",
        HightohighInputMin: "",
        HightohighInputMax: "",
        LowtolowInputMin: "",
        LowtolowInputMax: "",
        FlowerHeightMin: "",
        FlowerHeightMax: "",
        elasticradio: "",
        Machinemodelradio: "",
        NumberOfStitchesradio: "",
        Machinefunctionradio: "",
        texturesradio: "",
        structureradio: "",
        ScreeningConditionsradio: "",

        materialstateClassification: [],
        overlockstateClassification: [],
        ElementdescriptionstateClassification: [],
        PatternstylestateClassification: [],
        InventorystateClassification: [],

        materialstate: null,
        overlockstate: null,
        Elementdescriptionstate: null,
        Patternstylestate: null,                    
        Inventorystate: null,                    
        yearvalue: "",
        DevelopmentSeasonvalue: "",
        customervalue:"",
        keyword: ""
      },
      uid: 0,
      baseurl: api_url,
      // 购物车
      shopCart: [],
      shopNum: 0,
      GetpatternNum:[],
    };
  },
  computed: {
    ...mapState("user", ["session", "account"]),
  },
  created() {
    this.Getpattern();
    this.uid = this.session.id;
    this.getList();
    this.getCartList();
    this.getConfig();
    this.getCustomer();
  },

  methods: {
    imgSaveToUrl(name){  // 用event或file
        this.cropperName = name;
        this.cropperModel = true
    },
    //图片上传成功后
    handleUploadSuccess (data){
      this.searchPicture = data.data.path;
      this.fileLista = [];
      this.fileLista.push({url:this.baseurl + data.data.path});
      this.cropperModel = false;
      let PictureSearch = document.getElementsByClassName('PictureSearch')[0];
      PictureSearch.firstElementChild.lastElementChild.style.display = 'block';
    },
    del(file, fileList){
      this.fileLista = fileList;
      this.searchPicture = '';
      let PictureSearch = document.getElementsByClassName('PictureSearch')[0];
      PictureSearch.firstElementChild.lastElementChild.style.display = 'none';
    },
    changeCustomer(customer) {
      this.order.cstmr_num = customer.usercode;
      this.order.cstmr_name = customer.username;
      this.order.cstmr_id = customer.id;
    },
    getCustomer() {
        searchCustomer()
          .then((res) => {
            this.customers = res.data;
          })
          .catch((error) => {
            console.log("getCustomer error", error);
          });

    },
    getConfig() {
      getConfigJSON({})
        .then((res) => {
          let data = res.data;
          this.DevelopmentSeason = data.search_season;
          this.year = data.search_year;
        })
        .catch((error) => {
          console.log("studentSourceList error", error);
        });
    },
    ExpandPictureSearch() {
      let Mainheight = document.getElementsByClassName("divMain")[0];
      // let mheight = Number(this.Mainheight.replace("height: ", "").replace("px;", ""));
      if (this.PictureSearchClass !== "PictureSearchflex") {
        this.PictureSearchClass = "PictureSearchflex";
        // console.log(this.PictureSearchClass);
        // console.log(document.getElementsByClassName('divMain')[0]);
        // Mainheight.style.height = "1610px";
        // Mainheight.style.height = "2680px";

        Mainheight.style.height = `${Mainheight.offsetHeight + 180}px`;
        // console.log(this.Mainheight);
        // console.log(Mainheight.offsetHeight);
        this.isTextSearch = false;
      } else {
        this.isTextSearch = true;
        this.PictureSearchClass = "PictureSearchnoen";
        // Mainheight.style.height = "1445px";
        // Mainheight.style.height = "2515px";
        Mainheight.style.height = `${Mainheight.offsetHeight - 180}px`;
        // console.log(this.Mainheight);
        // console.log(Mainheight.offsetHeight);
      }
    },

    handleClick(tab, event) {
      console.log(tab, event);
    },

    UpdateUse(event, id) {
      for (let index = 0; index < this.use.length; index++) {
        this.use[index].class = "useNone";
      }
      this.use[id - 1].class = "useBlock";

      if (id == 1) {
        this.ClothingStyle = this.Underwear;
      } else if (id == 2) {
        this.ClothingStyle = this.coat;
      } else if (id == 3) {
        this.ClothingStyle = [{ id: 1, name: "无" }];
      } else if (id == 4) {
        this.ClothingStyle = [{ id: 1, name: "无" }];
      }
    },
    UpdateScreeningConditions(event, id) {
      for (let index = 0; index < this.ScreeningConditions.length; index++) {
        this.ScreeningConditions[index].class = "useNone";
      }
      this.ScreeningConditions[id - 1].class = "useBlock";

      if (id == 1) {
        this.FilterCriteriaDetails = this.material;
      } else if (id == 2) {
        this.FilterCriteriaDetails = this.overlock;
      } else if (id == 3) {
        this.FilterCriteriaDetails = this.Elementdescription;
      } else if (id == 4) {
        this.FilterCriteriaDetails = this.Patternstyle;
      }else if (id == 5) {
        this.FilterCriteriaDetails = this.inventory;
      }
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    },
    // 花型列表
    getList() {
      patternSearch(this.getListData)
        .then((res) => {
          this.tableData = res.data.items;
          this.totalPage = res.data.total;

          this.getListData.materialstateClassification = []
          this.getListData.overlockstateClassification = []
          this.getListData.ElementdescriptionstateClassification = []
          this.getListData.PatternstylestateClassification = []
          this.getListData.InventorystateClassification = []
          this.listLoading = false;
        })
        .catch((error) => {
          console.log("studentSourceList error", error);
        });
    },
    // 购物车列表
    getCartList() {
      cartList({ uid: this.uid })
        .then((res) => {
          this.shopCart = res.data;
          this.shopNum = this.shopCart.length;
        })
        .catch((error) => {
          console.log("cartList error", error);
        });
    },
    // 购物车删除
    Orderblockdelete(pid, uuid) {
      let index = 0;

      for (let i = 0; i < this.shopCart.length; i++) {
        if (this.shopCart[i].uuid == uuid) {
          index = i;
        }
      }

      cartDelete({ uid:this.uid, pid, index: index })
        .then((res) => {
          Message({
            message: "删除成功",
            type: "success",
            duration: 2 * 1000,
          });
          this.getCartList();
        })
        .catch((error) => {
          console.log("cartList error", error);
        });
    },
    // 购物车商品数量
    handleNum(pid, num) {
      cartNum({ uid: this.uid, pid, num })
        .then((res) => {})
        .catch((error) => {
          console.log("cartList error", error);
        });
    },
    // 购物车添加
    addCart(pid, no, series, picture) {
      this.$confirm("确认加入购物车?", "确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let title = '';
          // console.log(this.session.account_type);
          if (this.session.account_type == 1) {
            title = `${no}`;
          }else if (undefined == series) {
            title = `${no}`;
          } else{
            title = `${no}(${series})`;
          }

          let info = { id: pid, title, img: picture };
          info = JSON.stringify(info);
          cartAdd({ uid: this.uid, pid, num: 1, info })
            .then((res) => {
              Message({
                message: "添加成功",
                type: "success",
                duration: 2 * 1000,
              });
              this.getCartList();
            })
            .catch((error) => {
              console.log("cartList error", error);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    toInfo(pid) {
      this.$router.replace({ path: `/search/flowerInfo/${pid}/1/1` });
    },

    OrderIsBuy(){
       if (this.shopCart.length <= 0) {
        Message({
          message: "购物车为空!",
          type: "error",
          duration: 2 * 1000,
        });
        return;
      }

      let pids = [];
      this.shopCart.forEach((item) => {
          pids.push(item.id);
      });

      let aid = ""
      if(this.session.role_id == 2 || this.session.role_id == 6 ){
        aid = "0"
      }else{
        aid = this.order.cstmr_id
      }

      OrderIsBuy({account_id:aid,pids:pids}).then((res) =>{
        if(res.data.length <= 0){
          this.placeOrder()
        }else{
          let flowerNo = "";
          res.data.forEach(v => {
              if(flowerNo == ""){
                flowerNo += v
              }else{
                flowerNo += ","+v
              }
          });
          this.$confirm("该客户无这些花型编号的权限("+flowerNo+"),请确认后下单", "确认", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
             this.placeOrder();
          }) .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
        }
      })
    },
    placeOrder() {
      if (this.shopCart.length <= 0) {
        Message({
          message: "购物车为空!",
          type: "error",
          duration: 2 * 1000,
        });
        return;
      }
      this.$refs["order"].validate((valid) => {
        if (valid) {
          this.order.goods = [];
          this.shopCart.forEach((item) => {
            this.order.goods.push({ color: item.color, pid: item.id, num: item.num });
          });

          orderAdd(this.order)
            .then((res) => {
              Message({
                message: "下单成功!",
                type: "success",
                duration: 2 * 1000,
              });
              this.dialogVisible = false;
              this.getCartList();
            })
            .catch((error) => {
              console.log("cartList error", error);
            });
          return;
        } else {
          return false;
        }
      });
    },

    Becomeobject(value, cla) {
      let array = [];
      let obj = {};

      for (let index = 0; index < value.length; index++) {
        array.push(
          (obj = Object.assign(
            {},
            obj,
            { id: index + 1 },
            { name: value[index] },
            { class: cla }
          ))
        );
      }
      return array;
    },
    Getpattern() {
      getProperty().then((res) => {

        let num = this.GetpatternNum;
        for (let index = 0; index < res.data.length; index++) {  
          if(res.data[index].key_name != null || res.data[index].key_name != 'undefined'){
            num.push(res.data[index].key_name);
          }      
        }
        this.material = this.Becomeobject(
          res.data[num.indexOf("材料")].value.options
        );
        this.elastic = this.Becomeobject(
          res.data[num.indexOf("弹性")].value.options
        );
        this.use = this.Becomeobject(
          res.data[num.indexOf("用途")].value.options,
          "useNone"
        );
        this.Underwear = this.Becomeobject(
          res.data[num.indexOf("款式")].value.options[0]
        );
        this.coat = this.Becomeobject(
          res.data[num.indexOf("款式")].value.options[1]
        );
        this.Patternstyle = this.Becomeobject(
          res.data[num.indexOf("风格")].value.options
        );
        this.Inventory = this.Becomeobject(
          res.data[num.indexOf("库存条件")].value.options
        );
        this.Elementdescription = this.Becomeobject(
          res.data[num.indexOf("元素描述")].value.options
        );
        this.Machinefunction = this.Becomeobject(
          res.data[num.indexOf("功能")].value.options
        );
        this.overlock = this.Becomeobject(
          res.data[num.indexOf("波边")].value.options
        );
        this.Machinemodel = this.Becomeobject(
          res.data[num.indexOf("机型")].value.options
        );
        this.NumberOfStitches = this.Becomeobject(
          res.data[num.indexOf("机台针数")].value.options
        );
        this.textures = this.Becomeobject(
          res.data[num.indexOf("质感")].value.options
        );
        this.structure = this.Becomeobject(
          res.data[num.indexOf("结构")].value.options
        );
        // this.xxxxxxxxx          = this.Becomeobject(res.data[num.indexOf('系列')].value.options);
        // console.log(this.material);
        this.materialDictionaries = res.data[num.indexOf("材料")].value.options;
        this.overlockDictionaries = res.data[num.indexOf("波边")].value.options;
        this.ElementdescriptionDictionaries =
          res.data[num.indexOf("元素描述")].value.options;
        this.PatternstyleDictionaries =
          res.data[num.indexOf("风格")].value.options;
        this.InventoryDictionaries =
          res.data[num.indexOf("库存条件")].value.options;
      });
    },
    updateandoror() {
      this.getListData.materialstate = this.ScreeningConditions[0].state;
      this.getListData.overlockstate = this.ScreeningConditions[1].state;
      this.getListData.Elementdescriptionstate =
        this.ScreeningConditions[2].state;
      this.getListData.Patternstylestate = this.ScreeningConditions[3].state;
      this.getListData.Inventorystate = this.ScreeningConditions[4].state;
    },
    // FilterCriteriaDetailscheckboxClassification() {
    //   // console.log(this.FilterCriteriaDetailscheckbox);
    //   for (
    //     let index = 0;
    //     index < this.FilterCriteriaDetailscheckbox.length;
    //     index++
    //   ) {
    //     //检索materialDictionaries，分类至materialClassification
    //     if (
    //       this.materialDictionaries.indexOf(
    //         this.FilterCriteriaDetailscheckbox[index]
    //       ) !== -1
    //     ) {
    //       // console.log(this.materialDictionaries);
    //       // console.log(this.materialDictionaries.indexOf(this.FilterCriteriaDetailscheckbox[index]));
    //       this.getListData.materialstateClassification.push(
    //         this.materialDictionaries[
    //           this.materialDictionaries.indexOf(
    //             this.FilterCriteriaDetailscheckbox[index]
    //           )
    //         ]
    //       );
    //       // console.log(this.getListData.materialstateClassification);
    //     }
    //     if (
    //       this.overlockDictionaries.indexOf(
    //         this.FilterCriteriaDetailscheckbox[index]
    //       ) !== -1
    //     ) {
    //       this.getListData.overlockstateClassification.push(
    //         this.overlockDictionaries[
    //           this.overlockDictionaries.indexOf(
    //             this.FilterCriteriaDetailscheckbox[index]
    //           )
    //         ]
    //       );
    //       // console.log(this.getListData.overlockstateClassification);
    //     }
    //     if (
    //       this.ElementdescriptionDictionaries.indexOf(
    //         this.FilterCriteriaDetailscheckbox[index]
    //       ) !== -1
    //     ) {
    //       this.getListData.ElementdescriptionstateClassification.push(
    //         this.ElementdescriptionDictionaries[
    //           this.ElementdescriptionDictionaries.indexOf(
    //             this.FilterCriteriaDetailscheckbox[index]
    //           )
    //         ]
    //       );
    //       // console.log(this.getListData.ElementdescriptionstateClassification);
    //     }
    //     if (
    //       this.PatternstyleDictionaries.indexOf(
    //         this.FilterCriteriaDetailscheckbox[index]
    //       ) !== -1
    //     ) {
    //       this.getListData.PatternstylestateClassification.push(
    //         this.PatternstyleDictionaries[
    //           this.PatternstyleDictionaries.indexOf(
    //             this.FilterCriteriaDetailscheckbox[index]
    //           )
    //         ]
    //       );
    //       // console.log(this.getListData.PatternstylestateClassification);
    //     }
    //   }
    // },
  },
};
</script>


<style>
/* 外层 */
.divMain {
  width: 1641px;
  margin: 15px auto;
  border-radius: 10px;
  box-shadow: 3px 3px 12px 5px rgba(0, 0, 0, 0.15);
  background-color: #fbfbfb;
  padding: 0px;
  position: relative;
}

/* 订单列表外 */
.Orderlist {
  font-family: PingFang SC;
  font-style: normal;
  font-weight: bold;
  font-size: 24px;
  line-height: 22px;
  width: 96px;
  height: 22px;
  position: absolute;
  right: 41px;
  bottom: 26px;
  color: #000000;
}
/* 订单列表内 */
.dialogTitle .el-dialog {
  background: #f3f3f3;
  border-radius: 20px;
  margin-top: 6vh !important;
}
.dialogTitle .el-dialog__title {
  font-family: Roboto;
  font-style: normal;
  font-weight: normal;
  font-size: 24px;
  color: #000000;
}
.Orderblock {
  width: 583px;
  height: 77px;
  margin-bottom: 6px;
  background: #ffffff;
  border-radius: 5px;
  position: relative;
}
.OrderblockTitle {
  font-family: PingFang SC;
  font-style: normal;
  font-weight: normal;
  font-size: 16px;
  line-height: 22px;
  color: #000000;
  position: absolute;
  top: 11px;
  left: 80px;
}
.Orderblock .el-input-number {
  position: absolute;
  top: 42px;
  left: 348px;
}
.Orderblockdelete {
  font-family: Alibaba PuHuiTi;
  font-style: normal;
  font-weight: normal;
  font-size: 20px;
  line-height: 22px;
  color: #ffffff;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 57px;
  height: 64px;
  background-color: #fb4f4f;
  position: absolute;
  left: 500px;
  top: 7px;
  user-select: none;
}
.OrderSelectionCustomer .el-input__inner {
  width: 170px;
  height: 35px;
  background: #ffffff;
  border-radius: 10px;
}
.OrderSelectionCustomer .el-input__icon {
  line-height: 30px;
}
.dialogtypeface {
  font-family: Roboto;
  font-style: normal;
  font-weight: normal;
  font-size: 16px;
  line-height: 22px;
  color: #000000;
  margin: 0px 36px 0 0;
}
.dialogflex {
  display: flex;
  align-items: center;
  margin: 20px 0 0 0;
}

/* 其他 */
.marginright1 {
  margin-right: 20px;
}
</style>
